<script setup lang="ts">
defineOptions({
  name: "FULLSCREEN_FAB_TOPOLOGY_SPECIFICGAS_CHLORINE"
});

// 拓扑图 气化科 CL2 供应系统 弹框

// path  /fullScreen/fab/topology/tooltip/specificGas/chlorine?pidCode=GC-CL2-01&eqpId=YDPYT11&specId=VMB-CL2-01D03_Stick2_YDPYT11_TORR&materialCode=GC01SG01CGAV01

import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { queryFabTodayData } from "@/api/modules/fab";
import dayjs from "dayjs";
import echartsCom from "@/views/common/components/echartsCom/index.vue";

const route = useRoute();
const loading = ref<boolean>(false);
const echartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);
const echartsOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);

const previewSpecData = ref<Record<string, any>>(null);
const lineType = ref<"all" | "up" | "down" | "">("all");
const lineTypeOption = ref<Array<any>>([
  {
    label: "双边",
    value: "all",
    disabled: false
  },
  {
    label: "上单边",
    value: "up",
    disabled: false
  },
  {
    label: "下单边",
    value: "down",
    disabled: false
  }
]);

const lineTypeChangeHandler = async (val?: string) => {
  const { hourValueList = [], specDetail = null } = previewSpecData.value;
  let name = "123";
  let data = [];
  let xAxisData = [];
  if (hourValueList?.length) {
    data = hourValueList.map(item => item.value);
    xAxisData = hourValueList.map(item => item.hourStr);
  }
  if (specDetail) {
    const { indicatorName = "", pointUnit = "" } = specDetail;
    name = `${indicatorName}${pointUnit ? "（" + pointUnit + "）" : ""}`;
  }
  switch (val) {
    case "up":
      initEcharts(["up"], name, data, xAxisData);
      break;
    case "down":
      initEcharts(["down"], name, data, xAxisData);
      break;
    default:
      initEcharts(["up", "down"], name, data, xAxisData);
      break;
  }
  await echartsComRef.value?.updateOption(true);
};

const getSingleSeries = (code: string, val = undefined, specColor = [], xAxisLen = 24, data = []): Record<string, any> => {
  let name = code;
  const type = "line";
  let symbol = "none";
  let showSymbol = false;
  let color = "";
  let itemStyle = null;
  let endLabel = null;
  let lineStyle = null;
  if (data?.length === xAxisLen && !val && !specColor?.length) {
    symbol = "circle";
    showSymbol = true;
    color = "#666";
    itemStyle = {
      color
    };
    endLabel = {
      show: false
    };
    lineStyle = {
      color,
      width: 1
    };
  } else {
    name = name.toUpperCase();
    data = [];
    let num = 0;
    do {
      data.push(val);
      num++;
    } while (num < xAxisLen);
    color = specColor.find(item => item.code === `${code}Color`)?.colorValue || undefined;
    endLabel = {
      show: true,
      color,
      formatter: "{a}: {c}"
    };
    lineStyle = {
      color,
      width: 1,
      type: "dashed"
    };
  }
  return { name, type, symbol, showSymbol, itemStyle, data, endLabel, lineStyle };
};

const getEchartsSeries = (type?: "up" | "down" | "target" | "actual", name?: string, xAxisLen?: number, data?: Array<any>): Array<any> => {
  let uslValue = undefined;
  let uclValue = undefined;
  let uwlValue = undefined;
  let targetValue = undefined;
  let lwlValue = undefined;
  let lclValue = undefined;
  let lslValue = undefined;
  let specColor = [];

  const { specDetail = null } = previewSpecData.value;

  if (specDetail) {
    const {
      specDetail: {
        uslValue: uslValue_ = undefined,
        uclValue: uclValue_ = undefined,
        uwlValue: uwlValue_ = undefined,
        targetValue: targetValue_ = undefined,
        lwlValue: lwlValue_ = undefined,
        lclValue: lclValue_ = undefined,
        lslValue: lslValue_ = undefined,
        specColor: specColor_ = []
      }
    } = previewSpecData.value;

    uslValue = uslValue_;
    uclValue = uclValue_;
    uwlValue = uwlValue_;
    targetValue = targetValue_;
    lwlValue = lwlValue_;
    lclValue = lclValue_;
    lslValue = lslValue_;
    specColor = specColor_;
  }

  const ss = [];
  if (type === "up") {
    if (uslValue) {
      const s = getSingleSeries("usl", uslValue, specColor, xAxisLen, data);
      ss.push(s);
    }
    if (uclValue) {
      const s = getSingleSeries("ucl", uclValue, specColor, xAxisLen, data);
      ss.push(s);
    }
    if (uwlValue) {
      const s = getSingleSeries("uwl", uwlValue, specColor, xAxisLen, data);
      ss.push(s);
    }
  } else if (type === "down") {
    if (lwlValue) {
      const s = getSingleSeries("lwl", lwlValue, specColor, xAxisLen, data);
      ss.push(s);
    }
    if (lclValue) {
      const s = getSingleSeries("lcl", lclValue, specColor, xAxisLen, data);
      ss.push(s);
    }
    if (lslValue) {
      const s = getSingleSeries("lsl", lslValue, specColor, xAxisLen, data);
      ss.push(s);
    }
  } else if (type === "target") {
    const s = getSingleSeries("target", targetValue, specColor, xAxisLen, data);
    ss.push(s);
  } else if (type === "actual") {
    const ac = getSingleSeries(name, undefined, null, xAxisLen, data);
    ss.push(ac);
  }
  return ss;
};

const getDefaultXAxisData = () => {
  const xAxisData = [];
  let num = 0;
  do {
    const t = dayjs().subtract(num, "hour").format("HH:mm");
    xAxisData.unshift(t);
    num++;
  } while (num < 24);
  return xAxisData;
};

const initEcharts = (controlLine: Array<string> = [], name?: string, data?: Array<any>, xAxisData?: Array<any>) => {
  if (!previewSpecData.value) return null;
  const { specDetail = null } = previewSpecData.value;

  let min = undefined;
  let interval = undefined;
  let targetValue = undefined;
  let indicatorName = "";
  let pointUnit = "";
  if (specDetail) {
    const {
      specDetail: {
        startValue = undefined,
        step = undefined,
        targetValue: targetValue_ = undefined,
        indicatorName: indicatorName_ = "",
        pointUnit: pointUnit_ = ""
      }
    } = previewSpecData.value;
    min = startValue;
    interval = step;
    targetValue = targetValue_;
    indicatorName = indicatorName_;
    pointUnit = pointUnit_;
  }

  if (!xAxisData?.length) {
    xAxisData = getDefaultXAxisData();
  }
  const grid = {
    top: 28,
    bottom: 0,
    left: 16,
    right: 110,
    containLabel: true
  };
  const tooltip = {
    show: !!name && !!data?.length && !!xAxisData?.length
  };
  const xAxis = {
    name: "时间",
    type: "category",
    splitLine: {
      show: true
    },
    boundaryGap: false,
    data: xAxisData
  };
  const yAxis = {
    type: "value",
    name: `${indicatorName}${pointUnit ? "（" + pointUnit + "）" : ""}`,
    nameTextStyle: {
      align: "left"
    },
    splitLine: {
      show: true
    },
    min,
    interval
  };
  const series = [];
  if (controlLine.includes("up")) {
    let s = [];
    if (name && data?.length && xAxisData?.length) {
      s = getEchartsSeries("up", name, data.length, data);
    } else {
      s = getEchartsSeries("up");
    }
    series.push(...s);
  }
  if (controlLine.includes("down")) {
    let s = [];
    if (name && data?.length && xAxisData?.length) {
      s = getEchartsSeries("down", name, data.length, data);
    } else {
      s = getEchartsSeries("down");
    }
    series.push(...s);
  }

  if (targetValue) {
    let t = [];
    if (name && data?.length && xAxisData?.length) {
      t = getEchartsSeries("target", name, data.length, data);
    } else {
      t = getEchartsSeries("target");
    }
    series.push(...t);
  }

  if (name && data?.length && xAxisData?.length) {
    const ac = getEchartsSeries("actual", name, data.length, data);
    series.push(...ac);
  }
  echartsOptions.value = { grid, tooltip, xAxis, yAxis, series };
};

const init = async () => {
  loading.value = true;
  const {
    query: { pidCode = "", eqpId = "", specId = "", materialCode = "" }
  } = route;
  const params = { pidCode, eqpId, specId, materialCode };
  const res = await queryFabTodayData(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res) return;
  previewSpecData.value = res;
  const { specDetail = null } = res;
  let controlLine = [];
  if (specDetail) {
    controlLine = specDetail?.controlLine;
  }

  for (const item of lineTypeOption.value) {
    if (item.value === "all") {
      item.disabled = controlLine?.length !== 2;
    } else {
      item.disabled = !controlLine?.includes(item.value);
    }
  }

  if (controlLine?.length === 2) {
    lineType.value = "all";
  } else if (controlLine?.length === 1) {
    lineType.value = controlLine[0];
  } else {
    lineType.value = "";
  }
  await lineTypeChangeHandler();
};

init();
</script>

<template>
  <div class="topology-common-popup-base">
    <div class="common-popup-content-content">
      <div class="content-search">
        <px-radio-group v-model="lineType" @change="lineTypeChangeHandler">
          <px-radio-button v-for="item in lineTypeOption" :key="item.value" :label="item.value" :disabled="item.disabled">{{
            item.label
          }}</px-radio-button>
        </px-radio-group>
      </div>
      <div v-loading="loading" class="content-echarts">
        <echartsCom ref="echartsComRef" :options="echartsOptions" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.topology-common-popup-base {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;

  .common-popup-content-content {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 100%;
    height: 100%;
    padding: 16px;

    .content-search {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
    }

    .content-echarts {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      width: 100%;
    }
  }
}
</style>
